package naive;

import java.util.Random;

import skeleton.Board;
import skeleton.ChessInfo;
import skeleton.Solution;
import util.ForbiddenChecker;
import util.Pair;
import static util.ForbiddenChecker.*;

public class NaiveSolution implements Solution {
	int myColor, opColor;
	ForbiddenChecker fchecker = new ForbiddenChecker();
	boolean RANDOM = false;

	@Override
	public int solve(Board board, ChessInfo info) {
		myColor = info.color;
		opColor = (myColor == BLACK) ? WHITE : BLACK;

		int[][] score = new int[LEN][LEN];
		int[] directx = { 0, 1, 1, 1, 0, -1, -1, -1 };
		int[] directy = { -1, -1, 0, 1, 1, 1, 0, -1 };
		int best = 0;
		for (int i = 0; i < LEN; ++i)
			for (int j = 0; j < LEN; ++j)
				if (valid(board.data, i, j)) {
					for (int k = 0; k < 8; ++k) {
						int a, b;
						a = i + directx[k];
						b = j + directy[k];
						if (!outBound(a, b))
							if (board.data[a][b] == opColor)
								score[i][j] += 2;
							else if (board.data[a][b] == myColor)
								score[i][j] += 3;
					}
					if (score[i][j] > best)
						best = score[i][j];
				}
		if (best == 0) {
			if (valid(board.data, LEN / 2, LEN / 2)) {
				info.row = (byte) (LEN / 2);
				info.col = (byte) (LEN / 2);
				return NORMAL;
			}
		}
		Pair[] allPos = new Pair[LEN * LEN];
		int l = 0;
		for (int i = 0; i < LEN; ++i)
			for (int j = 0; j < LEN; ++j)
				if (score[i][j] == best) {
					allPos[l] = new Pair();
					allPos[l].first = i;
					allPos[l].second = j;
					++l;
				}
		if (l == 0) {
			for (int i=0; i<LEN; ++i)
				for (int j=0; j<LEN; ++j)
					if (valid(board.data, i, j)) {
						allPos[l] = new Pair();
						allPos[l].first = i;
						allPos[l].second = j;
						++l;
					}
		}
		
		int s;
		if (RANDOM)
			s = new Random().nextInt(l);
		else
			s = 0;
		info.row = (byte) allPos[s].first;
		info.col = (byte) allPos[s].second;
		return NORMAL;
	}

	private boolean outBound(int a, int b) {
		if (a < LEN && a >= 0 && b < LEN && b >= 0)
			return false;
		return true;
	}

	private boolean valid(int[][] board, int x, int y) {
		if (board[x][y] != EMPTY) return false;
		if (myColor == WHITE)
			return true;
		return fchecker.forbiddenCheck(board, x, y) == NO_FORBIDDEN;
	}
}
